package com.yangcan.code;

import java.io.IOException;
import java.lang.reflect.Field;

import com.dtr.zbar.build.ZBarDecoder;
import com.yangcan.code.scanbar.BeepManager;
import com.yangcan.code.scanbar.BitmapFileUtils;
import com.yangcan.code.scanbar.Bmp2YUV;
import com.yangcan.code.scanbar.CameraManager;
import com.yangcan.code.scanbar.CameraPreview;
import com.yangcan.code.scanbar.FileUtils;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import dome.app.com.zbar.R;


public class ScanActivity extends Activity {
	private FrameLayout scanPreview;
	private RelativeLayout scanContainer;
	private RelativeLayout scanCropView;
	private ImageView scanLine;
	private BeepManager beepManager;
	private Camera mCamera;
	private CameraPreview mPreview;
	private Handler autoFocusHandler;
	private CameraManager mCameraManager;
	private boolean barcodeScanned = false;
	private boolean previewing = true;
	private Rect mCropRect = null;
	private String result;
	private Vibrator vibrator;
	private Context mCont;
	private TextView iv_light;
	private TextView qrcode_g_gallery;
	private TextView tv_scan_result;
	private TextView mTvLight;
	private String paytype;
	private boolean isOpenLight = false;
	private String photo_path = null;
	public static final int PHOTOREQUESTCODE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_scan_qrcode);
		beepManager = new BeepManager(this);
		vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
		init();
		initListener();
	}

	private void init() {
		iv_light = (TextView) findViewById(R.id.iv_light);
		qrcode_g_gallery = (TextView) findViewById(R.id.qrcode_g_gallery);
		mTvLight = (TextView) findViewById(R.id.qrcode_open_light);
		scanPreview = (FrameLayout) findViewById(R.id.capture_preview);
		scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
		scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
		scanLine = (ImageView) findViewById(R.id.capture_scan_line);

	}

	@Override
	public void onResume() {
		super.onResume();
		restartCamera();
	}

	public void initListener() {
		iv_light.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (isOpenLight) {
					mTvLight.setText("关灯");
					isOpenLight = false;
				} else {
					mTvLight.setText("开灯");
					isOpenLight = true;
				}
				swichLight(isOpenLight);
			}
		});
		qrcode_g_gallery.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				showPictures(PHOTOREQUESTCODE);
			}
		});
		scanContainer.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {

			}
		});
	}

	private void vib() {
		try {
			vibrator.vibrate(500);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void swichLight(boolean islight) {
		mCameraManager.isFlashlight(islight);
	}

	@Override
	public void onPause() {
		super.onPause();
		releaseCamera();
	}

	private void releaseCamera() {
		if (mCamera != null) {
			previewing = false;
			mCamera.setPreviewCallback(null);
			mCamera.release();
			scanPreview.removeAllViews();
			mCamera = null;
			mCameraManager.closeDriver();
		}
	}

	private void restartCamera() {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		autoFocusHandler = new Handler();
		mCameraManager = new CameraManager(ScanActivity.this);
		try {
			mCameraManager.openDriver();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mCamera = mCameraManager.getCamera();
		mPreview = new CameraPreview(ScanActivity.this, mCamera, previewCb, autoFocusCB);
		scanPreview.removeAllViews();
		scanPreview.addView(mPreview);
		previewing = true;

		TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
				0.85f);
		animation.setDuration(3000);
		animation.setRepeatCount(-1);
		animation.setRepeatMode(Animation.REVERSE);
		scanLine.startAnimation(animation);

		if (barcodeScanned) {
			barcodeScanned = false;
			mCamera.setPreviewCallback(previewCb);
			mCamera.startPreview();
			previewing = true;
			mCamera.autoFocus(autoFocusCB);
		}
	}

	PreviewCallback previewCb = new PreviewCallback() {
		public void onPreviewFrame(byte[] data, Camera camera) {
			Size size = camera.getParameters().getPreviewSize();
			byte[] rotatedData = null;
			// 这里需要将获取的data翻转一下，因为相机默认拿的的横屏的数据
			rotatedData = new byte[data.length];
			for (int y = 0; y < size.height; y++) {
				for (int x = 0; x < size.width; x++)
					rotatedData[x * size.height + size.height - y - 1] = data[x + y * size.width];
			}

			// 宽高也要调整
			int tmp = size.width;
			size.width = size.height;
			size.height = tmp;
			initCrop();
			ZBarDecoder zBarDecoder = new ZBarDecoder();
			result = zBarDecoder.decodeCrop(rotatedData, size.width, size.height, mCropRect.left, mCropRect.top,
					mCropRect.width(), mCropRect.height());

			if (!TextUtils.isEmpty(result)) {
				beepManager.playBeepSound();
				vib();
				releaseCamera();
				onResult(result);
				return;
			} else

			{
				// MyLog.e("result is null");
			}
		}
	};

	// Mimic continuous auto-focusing
	AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
		public void onAutoFocus(boolean success, Camera camera) {
			autoFocusHandler.postDelayed(doAutoFocus, 1000);
		}
	};

	private Runnable doAutoFocus = new Runnable() {
		public void run() {
			if (previewing)
				mCamera.autoFocus(autoFocusCB);
		}
	};

	private float getDensity(Context context) {
		Resources resources = context.getResources();
		DisplayMetrics dm = resources.getDisplayMetrics();
		return dm.density;
	}

	/**
	 * 初始化截取的矩形区域
	 */
	private void initCrop() {
		int cameraWidth = mCameraManager.getCameraResolution().y;
		int cameraHeight = mCameraManager.getCameraResolution().x;

		/** 获取布局中扫描框的位置信息 */
		int[] location = new int[2];
		scanCropView.getLocationInWindow(location);

		int cropLeft = location[0];
		int titleHeight = (int) (56 * getDensity(ScanActivity.this));
		int cropTop = location[1] - getStatusBarHeight() - titleHeight;

		int cropWidth = scanCropView.getWidth();
		int cropHeight = scanCropView.getHeight();

		/** 获取布局容器的宽高 */
		int containerWidth = scanContainer.getWidth();
		int containerHeight = scanContainer.getHeight();

		/** 计算最终截取的矩形的左上角顶点x坐标 */
		int x = cropLeft * cameraWidth / containerWidth;
		/** 计算最终截取的矩形的左上角顶点y坐标 */
		int y = cropTop * cameraHeight / containerHeight;

		/** 计算最终截取的矩形的宽度 */
		int width = cropWidth * cameraWidth / containerWidth;
		/** 计算最终截取的矩形的高度 */
		int height = cropHeight * cameraHeight / containerHeight;

		// MyLog.e("x: " + x + "\n" + "y: " + y + "\n" + "cameraWidth: "
		// + cameraWidth + "\n" + "cameraHeight: " + cameraHeight + "\n"
		// + "containerWidth: " + containerWidth + "\n "
		// + "containerHeight: " + containerHeight + "width: " + width
		// + "\n" + "height: " + height);
		/** 生成最终的截取的矩形 */
		// mCropRect = new Rect(x, y, width + x, height + y);
		mCropRect = new Rect(0, 80, containerWidth, containerHeight);
	}

	private int getStatusBarHeight() {
		try {
			Class<?> c = Class.forName("com.android.internal.R$dimen");
			Object obj = c.newInstance();
			Field field = c.getField("status_bar_height");
			int x = Integer.parseInt(field.get(obj).toString());
			return getResources().getDimensionPixelSize(x);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 扫码结果
	 *
	 * @author chice.xu
	 * @date 2016-12-13
	 */

	public void onResult(final String result) {
		// 扫描到的内容
		if (!TextUtils.isEmpty(result)) {
			try {
				runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ScanActivity.this, result, Toast.LENGTH_LONG).show();
                        ScanActivity.this.finish();
                    }
                });
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public void setBitmap(Bitmap bitmap) {
		ImageView imageView = new ImageView(this);
		imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		imageView.setImageBitmap(bitmap);
		scanPreview.addView(imageView);

	}

	public void showPictures(int requestCode) {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, requestCode);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case PHOTOREQUESTCODE:
				Uri intentData = data.getData();
				if (intentData.toString().startsWith("content")) {
					String[] proj = { MediaStore.Images.Media.DATA };
					// 获取选中图片的路径
					Cursor cursor = getContentResolver().query(data.getData(), proj, null, null, null);

					if (cursor.moveToFirst()) {

						int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						photo_path = cursor.getString(column_index);
						if (photo_path == null) {
							photo_path = FileUtils.getPath(getApplicationContext(), data.getData());
						}
					}
					cursor.close();
				} else if (intentData.toString().startsWith("file")) {
					photo_path = intentData.getPath();
				}

				new Thread(new Runnable() {

					@Override
					public void run() {

						ZBarDecoder decoder = new ZBarDecoder();
						Bitmap bitmap = BitmapFileUtils.getDiskBitmap(photo_path);
						if (bitmap == null) {
							Toast.makeText(ScanActivity.this, "获取图片失败", Toast.LENGTH_LONG).show();
							;
							return;
						}
						bitmap = BitmapFileUtils.reduce(bitmap, 400, 400, true);
						int wi = bitmap.getWidth();
						int he = bitmap.getHeight();
						String qrcode = decoder.decodeRaw(Bmp2YUV.getYUV420sp(wi, he, bitmap), wi, he);
						onResult(qrcode);
						bitmap.recycle();
						bitmap = null;
					}
				}).start();
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
}
